<template>
    <el-dialog :title="titleMap[mode]" v-model="visible" :width="1800" destroy-on-close @closed="close" :close-on-click-modal="false" :close-on-press-escape="mode != 'show' ? false : true" align-center>
        <el-form :model="form" :rules="rules" :disabled="mode=='show'" label-width="100" ref="dialogForm">
            <el-row :gutter="1">
                <el-col :span="6">
                    <el-form-item label="地区" prop="area_id">
						<el-select v-model="form.area_id" placeholder="请选择" filterable clearable @change="areaChange">
							<el-option v-for="item in areaList" :key="item.id" :label="item.name" :value="item.id"></el-option>
						</el-select>
					</el-form-item>
                </el-col>
                <el-col :span="6">
                    <el-form-item label="日期" prop="send_date">
						<el-date-picker v-model="form.send_date" type="date" placeholder="请选择日期" :value-format="'YYYY-MM-DD'" style="width:100%"  @change="updateFields"/>
					</el-form-item>
                </el-col>
                <!-- <el-col :span="6">
                    <el-form-item label="码数" prop="area_id">
						<el-select v-model="form.area_id" placeholder="请选择" filterable clearable>
							<el-option v-for="item in areaList" :key="item.id" :label="item.name" :value="item.id"></el-option>
						</el-select>
					</el-form-item>
                </el-col> -->
                <el-col :span="6">
                    <el-form-item label="货柜号码" prop="container_code">
                        <el-input v-model="form.container_code" placeholder="请输入货柜号码" clearable @blur="updateFields"></el-input>
					</el-form-item>
                </el-col>
            </el-row>
            <el-row :gutter="1">
                <el-col :span="6">
                    <el-form-item label="船司" prop="shipping">
                        <el-input v-model="form.shipping" placeholder="请输入船司" clearable @blur="updateFields"></el-input>
					</el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="备注" prop="remark">
						<el-input v-model="form.remark" placeholder="备注" clearable @blur="updateFields"></el-input>
					</el-form-item>
                </el-col>
            </el-row>

            <div class="top_flex">
                <div style="width: 60%;">
                    <span>新增</span>
                    <div style="display: flex;align-items: center;">
                        <el-input v-model="bar_code" ref="barCodeInput" placeholder="放入条码" style="width: 200px" @keyup.enter="getTable()" :readonly="!form.area_id"></el-input>
                         <!-- @input="timeInput" -->
                        <el-tooltip content="录入条码需要先行选择地区" placement="top" width="200">
							<el-icon style="margin-left: 10px;" size="16"><el-icon-InfoFilled /></el-icon>
						</el-tooltip>
                        <span style="margin-left: 10px;font-weight: 600;font-size: 20px">总匹数: {{total_count}}</span>
                        <span style="margin-left: 10px;font-weight: 600;font-size: 20px">总码数: {{form.total_num}}</span>
                        <span style="margin-left: 10px;font-weight: 600;font-size: 20px">总货值: {{form.total_money}}</span>
                        <span style="margin-left: 10px;font-weight: 600;font-size: 20px">总重量: {{net_weight_total}}</span>
                    </div>
                </div>
                <!-- <div>
                    <span>检验单号</span>
                    <el-input v-model="test_code" placeholder="备注"></el-input>
                </div> -->
				<!-- <el-button type="primary" @click="order_detail = []" v-if="mode == 'add'">清空列表</el-button> -->
                <div>
                    <span>删除</span>
                    <el-input v-model="remove_bar_code" ref="removeBarCodeInput" placeholder="放入条码" @keyup.enter="removeCode"></el-input>
                </div>
            </div>
            <div style="height: 600px;margin-top: 35px;"><!-- display: flex;justify-content: center; -->
                <el-auto-resizer>
                    <template #default="{ width, height }">
                        <el-table-v2 border :columns="columns" :data="form.detail" :width="width" :height="height" row-key="index" @select-change="handleSelectChange" :row-height="40" />
                    </template>
                </el-auto-resizer>
            </div>
            <!-- <sc-form-table ref="table" v-model="form.detail" placeholder="暂无数据" hide-Add height="600" show-summary>
                <el-table-column label="条码" prop="roll_code" width="200"> </el-table-column>
                <el-table-column label="品名" prop="goods_name" width="200"> </el-table-column>
                <el-table-column label="货号" prop="goods_code" width="200"> </el-table-column>
                <el-table-column label="花型" prop="flower" width="200"> </el-table-column>
                <el-table-column label="颜色" prop="colorName" width="200"> </el-table-column>
                <el-table-column label="码数" prop="code_number"></el-table-column>
                <el-table-column label="指导价" prop="price"></el-table-column>
                <el-table-column label="合计" prop="total_price"></el-table-column>
            </sc-form-table> -->
        </el-form>
    </el-dialog>
    <price-volume v-if="dialog.save" ref="saveDialog" @success="handleSuccess" @closed="dialog.save = false"></price-volume>
</template>

<script>
import priceVolume from './priceVolume.vue';

import config from '@/config'
export default {
  components: { priceVolume },
    emits: ['success', 'closed'],
    data() {
        return {
            mode: "add",
            titleMap: {
                add: '新增发货单',
                copy: '新增发货单',
                edit: '编辑发货单',
                show: '查看发货单',
            },
            visible: false,
            isSaveing: false,
            form: {
                id: "",
                area_id: "",
                container_code: "",
                shipping: "",
                send_date: this.moment().format('YYYY-MM-DD'),
                remark: "",
                detail: [],
                total_num: "",
            },
            rules: {
                ware_id: [ {required: true, message: '请选择仓库'} ],
                send_date: [ {required: true, message: '请选择发货日期'} ],
            },
            areaList: [],
            bar_code: "",
            test_code: "",
            remove_bar_code: "",
            total_count: 0,
            net_weight_total: "",
            dialog: {
                save: false,
            },
            table_index: 0,
            columns: [
                {
                    title: '序号',
                    dataKey: 'index',
                    width: 80,
                    align: 'center'
                },
                {
                    title: '条码',
                    dataKey: 'roll_code',
                    width: 180,
                    align: 'center'
                },
                {
                    title: '品名(体积)',
                    dataKey: 'goods_name',
                    width: 180,
                    align: 'center',
                    cellRenderer: ({ rowData }) => {
                        return <div onClick={() => this.price_volume(rowData, '品名')} style="cursor: pointer;">{rowData.goods_name}</div>
                    }
                },
                {
                    title: '货号(备注)',
                    dataKey: 'goods_code',
                    width: 150,
                    align: 'center',
                    cellRenderer: ({ rowData }) => {
                        return <div onClick={() => this.price_volume(rowData, '货号')} style="cursor: pointer;">{rowData.goods_code}</div>
                    }
                },
                {
                    title: '花型(指导价)',
                    dataKey: 'flower',
                    width: 180,
                    align: 'center',
                    cellRenderer: ({ rowData }) => {
                        return <div onClick={() => this.price_volume(rowData, '指导价')} style="cursor: pointer; margin-bottom: 5px;">{rowData.flower}</div>
                    }
                },
                {
                    title: '颜色',
                    dataKey: 'color',
                    width: 150,
                    align: 'center'
                },
                {
                    title: 'Color',
                    dataKey: 'colorName',
                    width: 150,
                    align: 'center',
                    cellRenderer: ({ rowData }) => {
                        return rowData.colorName ? rowData.colorName : ''
                    }
                },
                {
                    title: '码数',
                    dataKey: 'code_number',
                    width: 100,
                    align: 'center'
                },
                {
                    title: '折码',
                    dataKey: 'folding',
                    width: 100,
                    align: 'center',
                    cellRenderer: ({ rowData }) => {
                        return rowData.folding ? rowData.folding : ''
                    }
                },
                {
                    title: '净重',
                    dataKey: 'net_weight',
                    width: 100,
                    align: 'center'
                },
                {
                    title: '克重',
                    dataKey: 'gram_weight',
                    width: 100,
                    align: 'center'
                },
                ...(this.$TOOL.data.get("COLUMNSAUTH").includes('send.base_price') ? [{ 
                    title: '成本价',
                    dataKey: 'base_price',
                    width: 100,
                    align: 'center'
                }] : []),
                {
                    title: '指导价',
                    dataKey: 'price',
                    width: 120,
                    align: 'center',
                    cellRenderer: ({ rowData, rowIndex }) => {
                        return (
                            <el-input 
                                v-model={rowData.price} 
                                ref={(el) => this.cacheInputRef(el, rowIndex)} // 动态引用
                                placeholder="体积" 
                                onFocus={(e) => this.common.inputFocus(e)}
                                onBlur={() => this.price_edit(rowData)}
                                onChange={() => this.music()}
                                onKeydown={(e) => this.handlePriceKeyDown(e, rowIndex)}
                                nativeOnFocus={(e) => e.target.select()} // 聚焦时全选文本
                            />
                        )
                    }
                },
                {
                    title: '备注',
                    dataKey: 'remark',
                    width: 150,
                    align: 'center',
                    cellRenderer: ({ rowData }) => {
                        return (
                            <el-input 
                                v-model={rowData.remark} 
                                placeholder="备注" 
                                clearable 
                                onBlur={() => this.remark_edit(rowData)}
                                onChange={() => this.music()}
                            />
                        )
                    }
                },
                {
                    title: '体积',
                    dataKey: 'volume',
                    width: 150,
                    align: 'center',
                    cellRenderer: ({ rowData }) => {
                        return (
                            <el-input 
                                v-model={rowData.volume} 
                                placeholder="体积" 
                                readonly 
                                onBlur={() => this.remark_edit(rowData)}
                                onChange={() => this.music()}
                            />
                        )
                    }
                },
                {
                    title: '供应商',
                    dataKey: 'apply_name',
                    width: 120,
                    align: 'center',
                    cellRenderer: ({ rowData }) => {
                        return rowData.apply_name ? rowData.apply_name : ''
                    }
                },
                {
                    title: '染厂',
                    dataKey: 'dye_factory_name',
                    width: 100,
                    align: 'center'
                },
                {
                    title: '加工厂',
                    dataKey: 'process_factory_name',
                    width: 100,
                    align: 'center'
                },
            ],
            inputRefs: new Map()
        }
    },
    created() {
        this.timeInput = this.common.debounce(this.timeInput, 5000);
        // this.removeCode = this.common.debounce(this.removeCode, 500);
	},
    mounted() {
		this.getArea();
    },
    methods: {
        // 缓存输入框引用
        cacheInputRef(el, rowIndex) {
            if (el) {
                this.inputRefs.set(rowIndex, el)
            } else {
                this.inputRefs.delete(rowIndex)
            }
        },
        handlePriceKeyDown(e, rowIndex) {
            if (e.key === 'ArrowUp' || e.key === 'ArrowDown' || e.key === 'Enter') {
                e.preventDefault()
                const direction = e.key === 'ArrowDown' || e.key === 'Enter' ? 1 : -1
                const targetIndex = rowIndex + direction
                // 确保在数据范围内
                if (targetIndex >= 0 && targetIndex < this.form.detail.length) {
                    this.$nextTick(() => {
                    const targetInput = this.inputRefs.get(targetIndex)
                    console.log('targetInput :>> ', targetInput);
                    if (targetInput && targetInput.focus) {
                        targetInput.focus()
                        // 确保获取到原生input元素
                        const nativeInput = targetInput.$el.querySelector('input')
                        if (nativeInput) nativeInput.select()
                    }
                    })
                }
            }
        },
        timeInput(){
            this.setData({id: this.form.id})
        },
        //显示
        open(mode = 'add') {
            this.mode = mode;
            this.visible = true;
            return this
        },
        close() {
            this.$emit('closed')
            this.submit()
        },
        //表单提交方法
        async submit() {
            if(!this.form.area_id) return
            if(this.mode == 'show') return
            if (this.form.id) {
                this.$emit('success', this.form, this.mode)
            } else {
                var res = await this.$API.ware.ware.send.add.post(this.form);
                if (res.code == 1) {
                    this.$emit('success', this.form, this.mode)
                    this.form.id = this.form.id?this.form.id:res.data.id
                }else {
                    this.$alert(res.message, "提示", {type: 'error'})
                    this.remove_bar_code = this.bar_code
                    this.removeCode()
                }
            }
        },
        //表单注入数据
        async setData(data) {
            if(data.id){
                setTimeout(()=>{
                    this.$nextTick(()=>{
                        this.$refs.barCodeInput.focus()
                    })
                },500)
            }
            this.form.id = data.id
            var res = await this.$API.ware.ware.send.detail.get({id: data.id});
            this.form.area_id = res.data.area_id
            this.form.container_code = res.data.container_code
            this.form.shipping = res.data.shipping
            this.form.send_date = res.data.send_date
            this.form.remark = res.data.remark
            this.total_count = res.data.total_count
            this.form.total_num = res.data.total_num
            this.form.total_money = res.data.total_money
            this.net_weight_total = res.data.net_weight_total
            this.table_index = res.data.detail.length
            let array = []
            res.data.detail.map(item=>{
                array.push({
                    id: item.id,
                    index: item.index,
                    inspect_id: item.inspect_id,
                    roll_code: item.inspect?.roll_code,
                    goods_code: item.inspect?.goods_code,
                    goods_name: item.inspect?.goods_name,
                    net_weight: item.inspect?.net_weight,
                    number: item.inspect?.number,
                    code_number: item.inspect?.code_number,
                    folding: item.inspect?.folding,
                    gram_weight: item.inspect?.gram_weight,
                    color: item.inspect?.color,
                    colorName: item.inspect?.color_en,
                    flower: item.inspect?.flower,
                    base_price: item.inspect?.base_price,
                    apply_name: item.inspect?.apply_name,
                    dye_factory_name: item.inspect?.dye_factory_name,
                    process_factory_name: item.inspect?.process_factory_name,
                    price: item.price,
                    remark: item.remark,
                    volume: item.volume,
                    total_price: (Number(item.price) * Number(item.inspect?.code_number)).toFixed(2),
                })
            })
            this.form.detail = array
        },
        // 地区列表
		async getArea() {
			var res = await this.$API.basic.area.all.get();
			this.areaList = res.data
		},
        async getTable(){
            if(!this.bar_code) return
            var res = await this.$API.ware.ware.scan.get({roll_code: this.bar_code,action_type: 1,send_id: this.form.id})
            if(res.code == 1){
                // 创建新的Audio实例播放成功声音，避免连续播放时相互干扰
                const successAudio = new Audio(`${config.API_URL}//audio/ok.wav`);
                successAudio.play();
                this.form.total_num = (Number(res.data.code_number) + Number(this.form.total_num)).toFixed(2)
                this.net_weight_total = (Number(res.data.net_weight) + Number(this.net_weight_total)).toFixed(2)
                const maxIndex = this.form.detail.length > 0 ? Math.max(...this.form.detail.map(item => item.index)) : 0
                const newIndex = maxIndex + 1
                this.table_index = newIndex
                let array = []
                let form = {
                    index: newIndex,
                    inspect_id: res.data.id,
                    roll_code: res.data.roll_code,
                    goods_code: res.data.goods_code,
                    goods_name: res.data.goods_name,
                    net_weight: res.data.net_weight,
                    code_number: res.data.code_number,
                    number: res.data.number,
                    folding: res.data.folding,
                    gram_weight: res.data.gram_weight,
                    color: res.data.color,
                    colorName: res.data.color_en,
                    flower: res.data.flower,
                    base_price: res.data.base_price,
                    apply_name: res.data.apply_name,
                    dye_factory_name: res.data.dye_factory_name,
                    process_factory_name: res.data.process_factory_name,
                    price: 0,
                    volume: res.data.goodsName?.volume,
                }
                this.bar_code = ""
                setTimeout(()=>{
                    array.push(form)
                    this.form.detail = [...array, ...this.form.detail]
                },10)
                this.total_count += 1
            }else{
                // 创建新的Audio实例播放错误声音，避免连续播放时相互干扰
                if(res.code == 0){
                    const errorAudio = new Audio(`${config.API_URL}/audio/error.wav`);
                    errorAudio.play();
                }else if(res.code == 2){
                    const doubleAudio = new Audio(`${config.API_URL}/audio/uk_double.wav`);
                    doubleAudio.play();
                }else if(res.code == 3){
                    const existentAudio = new Audio(`${config.API_URL}/audio/uk_non-existent.wav`);
                    existentAudio.play();
                }
                this.$message.error(res.message)
                this.$refs.barCodeInput.select()
            }
        },
        areaChange(){
            this.$nextTick(()=>{
                this.$refs.barCodeInput.focus()
            })
            if(this.form.id){
                this.updateFields()
            }else {
                this.submit()
            }
        },
        async removeCode(){
            if(!this.remove_bar_code) return
            var res = await this.$API.ware.ware.scan.get({roll_code: this.remove_bar_code,action_type: 2,send_id: this.form.id})
            if(res.code == 1){
                // 创建新的Audio实例播放成功声音，避免连续播放时相互干扰
                const successAudio = new Audio(`${config.API_URL}//audio/ok.wav`);
                successAudio.play();
                const index = this.form.detail.findIndex(item => item.roll_code == this.remove_bar_code)
                if(index !== -1){
                    this.$message.success("删除成功!")
                    this.form.detail.splice(index, 1)
                    this.form.total_num = this.form.detail.length ? (Number(this.form.total_num) - (Number(this.form.detail[index].code_number))).toFixed(2) : 0
                    this.net_weight_total = this.form.detail.length ? (Number(this.net_weight_total) - (Number(this.form.detail[index].net_weight))).toFixed(2) : 0 
                    // 添加条件判断，确保索引赋值的正确性
                    if (this.form.detail && this.form.detail.length > 0) {
                        // 先按原始索引排序，再重新赋值连续索引
                        const sortedItems = [...this.form.detail].sort((a, b) => a.index - b.index);
                        this.form.detail.forEach((item, idx) => {
                            // 查找当前项在排序后的位置，确保索引连续
                            const sortedIndex = sortedItems.findIndex(sortedItem => sortedItem.roll_code === item.roll_code);
                            item.index = sortedIndex !== -1 ? sortedIndex + 1 : idx + 1;
                        });
                        this.table_index = Math.max(...this.form.detail.map(item => item.index));
                    } else {
                        this.table_index = 0;
                    }
                    // this.submit()
                }else {
                    this.$message.error("此条数据不存在!")
                }
                // this.total()
                this.total_count -= 1
            }else {
                // 创建新的Audio实例播放错误声音，避免连续播放时相互干扰
                const errorAudio = new Audio(`${config.API_URL}/audio/error.wav`);
                errorAudio.play();
                this.$message.error(res.message)
                this.$refs.removeBarCodeInput.select()
            }
            this.remove_bar_code = ""
            this.bar_code = ""
        },
        price_volume(row,name){
            if(this.mode == 'show') return
            const goods_code_array = this.form.detail.filter(item=>item.goods_code == row.goods_code) 
            const new_array = this.form.detail.filter(item=>item.flower == row.flower) 
            let weight = 0
            new_array.map(item=>{
                weight += Number(item.net_weight)
            })
            goods_code_array.map(item=>{
                weight += Number(item.net_weight)
            })
            row.flower_length = new_array.length
            row.goods_code_length = goods_code_array.length
            row.flower_weight = (weight).toFixed(2)
            this.dialog.save = true
            this.$nextTick(() => {
                this.$refs.saveDialog.open('edit').setData(row,name)
            })
        },
        async handleSuccess(data,name,goods_code,flower,goods_name){
            let form = {}
            this.form.detail.forEach(item=>{
                if(name == '货号' && item.goods_code == goods_code){
                    item.remark = data.font
                    form = {
                        send_id: this.form.id,
                        remark: data.font,
                        goods_code: goods_code,
                    }
                } else if (name == '指导价' && item.flower == flower){
                    item.price = data.font
                    form = {
                        send_id: this.form.id,
                        price: data.font,
                        flower: flower,
                    }
                } else if (name == '品名' && item.goods_name == goods_name){
                    item.volume = data.font
                    form = {
                        send_id: this.form.id,
                        volume: data.font,
                        goods_code: goods_code,
                    }
                }
            })
            await this.$API.ware.ware.send.updateFieldsdetail.post(form);
            // setTimeout(()=>{
            //     this.setData({id: this.form.id})
            // },100)
        },


        async updateFields(){
            if(!this.form.area_id) return
            if(this.mode == 'show') return
            let form = {
                id: this.form.id,
                area_id: this.form.area_id,
                send_date: this.form.send_date,
                container_code: this.form.container_code,
                shipping: this.form.shipping,
                remark: this.form.remark,
                total_money: this.form.total_money,
                total_num: this.form.total_num,
            }
            await this.$API.ware.ware.send.updateFields.post(form);
            // const successAudio = new Audio(`${config.API_URL}//audio/ok.wav`);
            // successAudio.play();
        },
        music(){
            const successAudio = new Audio(`${config.API_URL}//audio/ok.wav`);
            successAudio.play();
        },

        async price_edit(row){
            let form = {
                send_id: this.form.id,
                send_detail_id: row.id,
                price: row.price,
            }
            await this.$API.ware.ware.send.updateFieldsdetail.post(form);
            this.total()
            // this.setData({id: this.form.id})
        },
        async remark_edit(row){
            let form = {
                send_id: this.form.id,
                send_detail_id: row.id,
                remark: row.remark,
            }
            await this.$API.ware.ware.send.updateFieldsdetail.post(form);
            // this.setData({id: this.form.id})
        },


        total(){
            let total_code_number = 0
            let total_money_number = 0
            this.form.detail.map(item=>{
                total_code_number = Number(item.code_number) + total_code_number
                if(item.price){
                    item.total_money = (Number(item.price) * Number(item.code_number)).toFixed(2)
                }
                total_money_number = Number(item.total_money) + total_money_number
            })
            this.form.total_num = (total_code_number).toFixed(2)
            this.form.total_money = (total_money_number).toFixed(2)
            this.updateFields()
        }
    }
}
</script>

<style lang="scss">
.top_flex{
    display: flex;
    justify-content: space-between;
}
</style>
